package com.sense.kukoo.common.media.timer

import android.os.Handler
import android.os.Looper
import com.sense.kukoo.common.media.Kukoo
import com.sense.kukoo.lib_logger.LoggerManager

class TimerImpl {

    private val TAG: String = javaClass.simpleName

    private val mHandler = Handler(Looper.getMainLooper())
    private val mDelayedTime = 1000L

    private var mCurrentType :Int = TYPE_OFF
    private var isLoop = false
    private var targetTimeMillis = 0L

    private val mRunnable:Runnable = object :Runnable{
        override fun run() {
            if (isLoop){
                refresh()
            }
        }
    }

    companion object{
        val TYPE_WHEN_CURRENT_EPISODE_END = -1
        val TYPE_90_MIN = 90
        val TYPE_60_MIN = 60
        val TYPE_45_MIN = 45
        val TYPE_30_MIN = 30
        val TYPE_15_MIN = 15
        val TYPE_OFF = 0
    }

    fun setTimer(type:Int){
        LoggerManager.d(TAG, "setTimer() type=${type}")
        mCurrentType = type
        when (mCurrentType) {
            TYPE_WHEN_CURRENT_EPISODE_END -> {
                stop()
            }
            TYPE_90_MIN -> {
                targetTimeMillis = System.currentTimeMillis() + 90 * 60 * 1000L
                setLooper(true)
            }
            TYPE_60_MIN -> {
                targetTimeMillis = System.currentTimeMillis() + 60 * 60 * 1000L
                setLooper(true)
            }
            TYPE_45_MIN -> {
                targetTimeMillis = System.currentTimeMillis() + 45 * 60 * 1000L
                setLooper(true)
            }
            TYPE_30_MIN -> {
                targetTimeMillis = System.currentTimeMillis() + 30 * 60 * 1000L
                setLooper(true)
            }
            TYPE_15_MIN -> {
                targetTimeMillis = System.currentTimeMillis() + 15 * 60 * 1000L
                setLooper(true)
            }
            TYPE_OFF -> {
                stop()
            }
            else -> {}
        }
    }

    fun isWhenCurrentEpisodeEnd():Boolean{
        return mCurrentType == TYPE_WHEN_CURRENT_EPISODE_END
    }

    fun onPlayNew(){
        if (isWhenCurrentEpisodeEnd()) {
            //When_Current_Episode_End 会自动失效
            setTimer(TYPE_OFF)
        }
    }

    private fun setLooper(loop:Boolean){
        if(isLoop != loop){
            isLoop = loop
            if (isLoop) {
                mHandler.post(mRunnable)
            }else{
                mHandler.removeCallbacks(mRunnable)
            }
        }
    }

    private fun refresh(){
        val left = targetTimeMillis - System.currentTimeMillis()
        if(left <= 0){
            onTimerFinish()
        }else{
            val leftStr = calculateTime(left.toInt())
            Kukoo.watcher.dispatchTimerEvent {
                onTimerChanged(mCurrentType, left, leftStr)
            }
            mHandler.postDelayed(mRunnable, mDelayedTime)
        }
    }

    private fun onTimerFinish(){
        setTimer(TYPE_OFF)
        LoggerManager.d(TAG, "onTimerFinish() 暂停音乐")
        Kukoo.play.pause()
    }

    private fun stop(){
        targetTimeMillis = 0L
        setLooper(false)
        Kukoo.watcher.dispatchTimerEvent {
            onTimerChanged(mCurrentType, 0L, "")
        }
    }

    private fun calculateTime(milliseconds:Int): String {
        val time: Int = milliseconds / 1000

        val minute: Int
        val second: Int
        return if (time >= 60) {
            minute = time / 60
            second = time % 60
            (if (minute < 10) "0$minute" else "" + minute) + if (second < 10) ":0$second" else ":$second"
        } else {
            second = time
            if (second < 10) {
                "00:0$second"
            } else "00:$second"
        }
    }

}